package com.crm.business.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.crm.business.crm.mapper.CrmSourceMapper;
import com.crm.business.crm.service.ICrmFieldService;
import com.crm.business.crm.service.ICrmSourceService;
import com.crm.common.crm.entity.BO.CrmSourceSearchBO;
import com.crm.common.crm.entity.PO.CrmField;
import com.crm.common.crm.entity.PO.CrmSource;
import com.crm.common.ka.core.entity.BasePage;
import com.crm.business.servlet.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CrmSourceServiceImpl extends BaseServiceImpl<CrmSourceMapper, CrmSource> implements ICrmSourceService {

    @Autowired
    private ICrmFieldService crmFieldService;

    @Override
    public List<CrmSource> querySourceDataGroupByCode() {
        return baseMapper.querySourceDataGroupByCode();
    }

    @Override
    public BasePage<CrmSource> queryList(CrmSourceSearchBO crmSource) {
        Integer count = baseMapper.queryListCount(crmSource);
        if(count == 0){
            BasePage<CrmSource> basePage = new BasePage<>(crmSource.getPage(),crmSource.getLimit());
            return basePage;
        }
        BasePage<CrmSource> basePage = new BasePage<>(crmSource.getPage(),crmSource.getLimit(),count);
        Integer pageStart = crmSource.getPage() > 0 ? (crmSource.getPage() - 1) * crmSource.getLimit() : 0;
        crmSource.setPage(pageStart);
        List<CrmSource> crmSourceList = baseMapper.queryList(crmSource);
        basePage.setList(crmSourceList);
        return basePage;
    }

    @Override
    public CrmSource queryInfoById(Integer id){
        return baseMapper.queryInfoById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addSource(CrmSource source) {
        QueryWrapper<CrmField> wrapper = new QueryWrapper<>();
        wrapper.eq("name","客户来源");
        List<CrmField> list = crmFieldService.list(wrapper);
        for (CrmField field : list) {
            try {
                String newOptions = field.getOptions() + "," + source.getSource();
                Integer result = crmFieldService.updateSourceOptions(newOptions, field.getFieldId());
                if(result <= 0 ){
                    throw new Exception("更新字段选项失败");
                }
            } catch (Exception exception) {
                exception.printStackTrace();
                return 0;
            }
        }
        return baseMapper.addSource(source);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSource(CrmSource source) {
        CrmSource oldSource = baseMapper.queryInfoById(source.getId());
        QueryWrapper<CrmField> wrapper = new QueryWrapper<>();
        wrapper.eq("name","客户来源");
        List<CrmField> list = crmFieldService.list(wrapper);
        for (CrmField field : list) {
            try {
                String newOptions = field.getOptions().replaceAll(oldSource.getSource(),source.getSource());
                Integer result = crmFieldService.updateSourceOptions(newOptions, field.getFieldId());
                if(result <= 0 ){
                    throw new Exception("更新字段选项失败");
                }
            } catch (Exception exception) {
                exception.printStackTrace();
                return 0;
            }
        }
        return baseMapper.updateSource(source);
    }

    /**
     * 删除投放金额数据
     *
     * @param ids ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Integer> ids) throws Exception {
        //要删除的客户来源
        List<CrmSource> sourceList = baseMapper.querySourceByIds(ids);
        // 字段表中客户来源
        QueryWrapper<CrmField> wrapper = new QueryWrapper<>();
        wrapper.eq("name","客户来源");
        List<CrmField> list = crmFieldService.list(wrapper);

        for (CrmField field : list) {
            String newOptions = "";
            for(CrmSource source : sourceList){
                String oldOptions = "";
                if(StringUtils.isNotEmpty(newOptions)){
                    oldOptions = newOptions;
                }else{
                    oldOptions = field.getOptions();
                }
                String[] oldOptionsArr = oldOptions.split(source.getSource());
                if(oldOptionsArr.length > 1){
                    if(StringUtils.isNotEmpty(oldOptionsArr[0]) && StringUtils.isNotEmpty(oldOptionsArr[1])){
                        newOptions = oldOptionsArr[0] + oldOptionsArr[1].substring(1);
                    }else if(StringUtils.isNotEmpty(oldOptionsArr[0]) && StringUtils.isEmpty(oldOptionsArr[1])){
                        newOptions = oldOptionsArr[0].substring(0,oldOptionsArr[0].length()-1);
                    }else{
                        newOptions = oldOptionsArr[1].substring(1);
                    }
                }else{
                    newOptions = oldOptionsArr[0].substring(0,oldOptionsArr[0].length()-1);
                }
            }
            Integer result = crmFieldService.updateSourceOptions(newOptions, field.getFieldId());
            if(result <= 0 ){
                throw new Exception("更新字段选项失败");
            }

        }

        baseMapper.deleteSourcesByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Integer id) throws Exception {
        //要删除的客户来源
        CrmSource source = baseMapper.queryInfoById(id);
        // 字段表中客户来源
        QueryWrapper<CrmField> wrapper = new QueryWrapper<>();
        wrapper.eq("name","客户来源");
        List<CrmField> list = crmFieldService.list(wrapper);
        for (CrmField field : list) {
            String newOptions = "";

            String oldOptions = field.getOptions();
            String[] oldOptionsArr = oldOptions.split(source.getSource());
            if(oldOptionsArr.length > 1){
                if(StringUtils.isNotEmpty(oldOptionsArr[0]) && StringUtils.isNotEmpty(oldOptionsArr[1])){
                    newOptions = oldOptionsArr[0] + oldOptionsArr[1].substring(1);
                }else if(StringUtils.isNotEmpty(oldOptionsArr[0]) && StringUtils.isEmpty(oldOptionsArr[1])){
                    newOptions = oldOptionsArr[0].substring(0,oldOptionsArr[0].length()-1);
                }else{
                    newOptions = oldOptionsArr[1].substring(1);
                }
            }else{
                newOptions = oldOptionsArr[0].substring(0,oldOptionsArr[0].length()-1);
            }
            Integer result = crmFieldService.updateSourceOptions(newOptions, field.getFieldId());
            if(result <= 0 ){
                throw new Exception("更新字段选项失败");
            }
        }
        baseMapper.deleteSourceById(id);
    }

}
